package database.service;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import database.auxiliary.LogGenerator;

import po.GiftPO;

public class GiftDataServiceSerializableImpl implements GiftDataService {

	private ArrayList<GiftPO> giftList;

	public GiftDataServiceSerializableImpl() {
		giftList = new ArrayList<GiftPO>();
	}

	@Override
	public void load() {
		try {
			File file = new File("data/gift.ser");
			if (!file.exists()) {
				file.createNewFile();
			}
			ObjectInputStream oiStream = new ObjectInputStream(
					new FileInputStream(file));
			GiftPO giftPO;
			while ((giftPO = (GiftPO) oiStream.readObject()) != null) {
				giftList.add(giftPO);
			}
			LogGenerator.log("Gift data load succeed");
		} catch (EOFException e) {
			save();
			load();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save() {
		try {
			FileOutputStream fos = new FileOutputStream("data/gift.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			for (int i = 0; i < giftList.size(); i++) {
				oos.writeObject(giftList.get(i));
			}
			oos.writeObject(null);
			oos.close();
			LogGenerator.log("Gift data save succeed");
		} catch (FileNotFoundException e) {
			System.out.println("File found failed!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public int insert(GiftPO gift) {
		gift.setId(giftList.size() + 1);
		giftList.add(gift);
		LogGenerator.log("Gift insert: " + gift);
		return giftList.size();
	}

	@Override
	public void delete(GiftPO gift) {
		for (int i = 0; i < giftList.size(); i++) {
			if (giftList.get(i).getId() == gift.getId()) {
				giftList.get(i).setId(-giftList.get(i).getId());
				LogGenerator.log("gift delete: " + gift);
			}
		}
	}

	@Override
	public void update(GiftPO gift) {
		for (int i = 0; i < giftList.size(); i++) {
			if (gift.getId() == giftList.get(i).getId()) {
				giftList.get(i).setId(gift.getId());
				LogGenerator.log("gift update: " + gift);
			}
		}
	}

	@Override
	public GiftPO find(int id) {
		for (int i = 0; i < giftList.size(); i++) {
			if (id == giftList.get(i).getId()) {
				LogGenerator.log("Gift find: " + giftList.get(i));
				return giftList.get(i);
			}
		}
		return null;
	}

	@Override
	public Iterator<GiftPO> getIterator() {
		LogGenerator.log("Gift return itr, length = " + giftList.size());
		return giftList.iterator();
	}

}
